import { TaskModel } from '../../../models/task'

const taskModel = new TaskModel()
const App = getApp()
Page({
  /**
     * 页面的初始数据
     */
  data: {
    newHand: true,
    tasks: [],
    code: '',
    newHandTasksImg: [
      '%ASSETS_IMG%/l-newyear-suofen1@2x.png?v=1',
      '%ASSETS_IMG%/l-newyear-suofen50@2x.png?v=1',
      '%ASSETS_IMG%/l-newyear-chengjiao@2x.png?v=1',
      '%ASSETS_IMG%/l-newyear-yongjin@2x.png?v=1',
      '%ASSETS_IMG%/l-newyear-suofen200@2x.png?v=1',
      '%ASSETS_IMG%/l-newyear-phone@2x.png?v=1',
      '%ASSETS_IMG%/l-newyear-share@2x.png?v=1'
    ],
    dayTasksImg: ['%ASSETS_IMG%/c-qiandao.png'],
    statusBarHeight: App.globalData.statusBarHeight,
    isTabbar: false
  },

  tapToDay: function(event) {
    this.getTasks(0, false)
  },
  tapToNewHand: function(event) {
    this.getTasks()
  },

  /**
     * 提交任务
     */
  submitTask: function(event) {
    const tid = event.detail.tid
    const that = this
    const index = event.detail.index
    const tmpTasks = this.data.tasks
    tmpTasks[index].rebateStatus = 2
    taskModel
      .pushTask({
        id: tid
      })
      .then(res => {
        wx.showToast({
          title: `成功领取${res.data.gold}金币`,
          duration: 2000,
          success: res => {
            that.setData({
              tasks: tmpTasks
            })
          }
        })
      })
  },

  /**
     * 生命周期函数--监听页面加载
     */
  onLoad: function(options) {},

  /**
     * 生命周期函数--监听页面初次渲染完成
     */
  onReady: function() {},

  /**
     * 生命周期函数--监听页面显示
     */
  onShow: function() {
    this.getTasks()
  },

  /**
     * 生命周期函数--监听页面隐藏
     */
  onHide: function() {},

  /**
     * 生命周期函数--监听页面卸载
     */
  onUnload: function() {},

  /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
  onPullDownRefresh: function() {},

  /**
     * 页面上拉触底事件的处理函数
     */
  onReachBottom: function() {},

  getTasks(status = 1, isNewHand = true) {
    let that = this
    const tasks = taskModel.getTasks({
      taskType: status
    })
    tasks.then(res => {
      //判断是否绑定手机号
      for (var i in res.data.taskList) {
        if (res.data.taskList[i].taskDetail == '绑定手机号') {
          if (res.data.taskList[i].rebateStatus == 0) {
            wx.login({
              success: function(res) {
                if (res.code) {
                  //发起网络请求
                  that.setData({
                    code: res.code
                  })
                } else {
                  console.log('获取用户登录态失败！' + res.errMsg)
                }
              }
            })
          }
        }
      }
      //隐藏粉丝任务

      that.setData({
        tasks: res.data.taskList,
        newHand: isNewHand
      })
    })
  }
})
